/**
 * @file IxOsalOsSemaphore.c (l4aos)
 *
 * @brief Implementation for semaphore and mutex.
 * 
 * 
 * @par
 * IXP400 SW Release version 2.1
 * 
 * -- Copyright Notice --
 * 
 * @par
 * Copyright (c) 2001-2005, Intel Corporation.
 * All rights reserved.
 * 
 * @par
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Intel Corporation nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * 
 * @par
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * 
 * @par
 * -- End of Copyright Notice --
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sel4/sel4.h>
#include <sync/sem.h>
#include <sync/mutex.h>

#include "ixp_osal/IxOsal.h"

extern void sos_usleep(int usecs);

PUBLIC IX_STATUS
ixOsalSemaphoreInit(IxOsalSemaphore *sid, UINT32 start_value) {
    sync_sem_t sem = sync_create_sem(start_value);
    if (!sem) {
        ixOsalLog(IX_OSAL_LOG_LVL_ERROR, IX_OSAL_LOG_DEV_STDOUT,
                "ixOsalSemaphoreInit: fail to allocate for semaphore \n", 0, 0, 0, 0, 0, 0);
        return IX_FAIL;
    }

    *sid = sem;

    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalSemaphoreWait(IxOsalOsSemaphore *sid, INT32 timeout) {
    sync_sem_t sem = *sid;
    if (timeout != IX_OSAL_WAIT_FOREVER) {
        IX_STATUS result = ixOsalSemaphoreTryWait(sid);
        if (result != IX_SUCCESS) {
            sos_usleep(timeout * 1000);
            result = ixOsalSemaphoreTryWait(sid);
        }
        return result;
    }

    sync_wait(sem);
    return IX_SUCCESS;
}

/* 
 * Attempt to get semaphore, return immediately,
 * no error info because users expect some failures
 * when using this API.
 */
PUBLIC IX_STATUS
ixOsalSemaphoreTryWait(IxOsalSemaphore *sid) {
    sync_sem_t sem = *sid;
    return sync_try_wait(sem) ? IX_SUCCESS : IX_FAIL;
}

/**
 *
 * DESCRIPTION: This function causes the next available thread in the pend queue
 *              to be unblocked. If no thread is pending on this semaphore, the 
 *              semaphore becomes 'full'. 
 */
PUBLIC IX_STATUS
ixOsalSemaphorePost(IxOsalSemaphore *sid) {
    sync_sem_t sem = *sid;
    sync_signal(sem);
    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalSemaphoreGetValue(IxOsalSemaphore * sid, UINT32 * value) {
    sync_sem_t sem = *sid;
    *value = sync_sem_value(sem);
    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalSemaphoreDestroy(IxOsalSemaphore *sid) {
    sync_sem_t sem = *sid;
    sync_destroy_sem(sem);
    return IX_SUCCESS;
}

/****************************
 *    Mutex 
 ****************************/
sync_mutex_t init_mutex = NULL;

#define UNINITIALISED_MUTEX 0xFFFFFFFF

/**
 * Initialise a mutex. This is done lazily, and needs to
 * be locked. Only one lock is used to init all mutexes
 * as we assume low contention.
 */
static IX_STATUS mutex_init(IxOsalMutex *mutexP) {
    if (*mutexP == (IxOsalMutex) UNINITIALISED_MUTEX) {

        sync_acquire(init_mutex);
        //it got initialised while we were waiting
        if (*mutexP != (IxOsalMutex) UNINITIALISED_MUTEX) {
            sync_release(init_mutex);
            return IX_SUCCESS;
        }

        sync_mutex_t mutex = sync_create_mutex();
        if (!mutex) {
            sync_release(init_mutex);
            return IX_FAIL;
        }
        *mutexP = mutex;
        sync_release(init_mutex);
    }
    return IX_SUCCESS;

}

PUBLIC IX_STATUS
ixOsalMutexInitLib(void) {

    init_mutex = sync_create_mutex();
    if (!init_mutex) {
        return IX_FAIL;
    }

    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalMutexInit(IxOsalMutex *mutexP) {

    //we lazily allocate mutexes to boost perf.
    *mutexP = (IxOsalMutex) UNINITIALISED_MUTEX;

    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalMutexLock(IxOsalMutex * mutex, INT32 timeout) {
    if (mutex_init(mutex) == IX_FAIL) {
        return IX_FAIL;
    }

    if (timeout != IX_OSAL_WAIT_FOREVER) {
        IX_STATUS result = ixOsalMutexTryLock(mutex);
        if (result != IX_SUCCESS) {
            sos_usleep(timeout * 1000);
            result = ixOsalMutexTryLock(mutex);
        }
        return result;
    }
    sync_acquire(*mutex);
    return IX_SUCCESS;
}

PUBLIC IX_STATUS
ixOsalMutexUnlock(IxOsalMutex * mutex) {
    assert(*mutex != (IxOsalMutex) UNINITIALISED_MUTEX);
    sync_release(*mutex);
    return IX_SUCCESS;
}

/* 
 * Attempt to get mutex, return immediately,
 * no error info because users expect some failures
 * when using this API.
 */
PUBLIC IX_STATUS
ixOsalMutexTryLock(IxOsalMutex * mutex) {
    if (mutex_init(mutex) == IX_FAIL) {
        return IX_FAIL;
    }

    IX_STATUS result = sync_try_acquire(*mutex);
    if (result) {
        return IX_SUCCESS;
    }
    return IX_FAIL;
}

PUBLIC IX_STATUS
ixOsalMutexDestroy(IxOsalMutex * mutex) {
    assert(*mutex != (IxOsalMutex) UNINITIALISED_MUTEX);
    sync_destroy_mutex(*mutex);
    return IX_SUCCESS;
}

